package com.xinyue.game.center.common;

import com.xinyue.game.jwt.GameJwtService;
import com.xinyue.game.jwt.GameRoleToken;
import com.xinyue.game.jwt.GameUserToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.time.Duration;

/**
 * @author 王广帅
 * @since 2023/5/30 20:44
 **/
@Service
public class GameTokenService {

    private static Logger logger = LoggerFactory.getLogger(GameTokenService.class);
    /**
     * jwt token管理类
     */
    private GameJwtService gameJwtService = new GameJwtService();

    @Autowired
    private GameCenterConfig gameCenterConfig;

    /**
     * 创建用户账号token
     *
     * @param userToken
     * @return
     */
    public String createAccountToken(GameUserToken userToken) {
        String token = this.createToken(userToken, userToken.getUserId());
        return token;
    }

    private String createToken(Object tokenData, String userId) {
        Duration periodTime = Duration.ofDays(gameCenterConfig.getTokenPeriodDay());
        byte[] key = gameCenterConfig.getTokenAesKey().getBytes(StandardCharsets.UTF_8);
        String token = gameJwtService.createJwtToken(tokenData, periodTime, key);
        logger.info("创建token成功，userId: {}, token: {}", userId, token);
        return token;
    }


    public String createPlayerToken(String userId, String playerId, String zoneId) {
        GameRoleToken gameToken = new GameRoleToken();
        gameToken.setPlayerId(playerId);
        gameToken.setUserId(userId);
        gameToken.setZoneId(zoneId);
        String roleToken = this.createToken(gameToken, gameToken.getPlayerId());
        return roleToken;
    }
}
